package models

import (
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"strings"
)

// 脚本
type K8sYamlTask struct {
	Model        // 不用每次写ID 和 createAt了
	Name  string `json:"name" validate:"required,min=1,max=50" gorm:"uniqueIndex;type:varchar(100);comment:任务脚本名称，支持使用通配符*进行模糊搜索" `
	//Creator User   `json:"Creator" `
	UserID      uint
	TemplateId  uint   `json:"templateId"`
	ClusterName string `json:"clusterName"`
	//FlowNodes     []FlowNode `json:"flowNodes" gorm:"foreignKey:K8sYamlTaskRefer"`
	// 一对多关系 https://gorm.io/zh_CN/docs/has_many.html
	Variables   StringArray `json:"variables" gorm:"type:text;comment:yaml的变量  k=v,k=v"`
	Status      string      `json:"status"  gorm:"comment:当前状态"`
	ApplyResult string      `json:"applyResult"  gorm:"comment:apply后的返回数据"`

	Key            string `json:"key" gorm:"-"`            //给前端表格
	VariablesFront string `json:"variablesFront" gorm:"-"` //给前端表格
	YamlString     string `json:"yamlString" gorm:"-"`     //给前端表格
	TemplateName   string `json:"templateName" gorm:"-"`   //给前端表格
	CreateUserName string `json:"createUserName" gorm:"-"`
}

func (obj *K8sYamlTask) Create() error {
	return Db.Create(obj).Error

}
func (obj *K8sYamlTask) DeleteOne() error {

	return Db.Select(clause.Associations).Unscoped().Delete(obj).Error

}

func (obj *K8sYamlTask) CreateOne() error {
	return Db.Create(obj).Error

}

func (obj *K8sYamlTask) UpdateOne() error {
	return Db.Where("id = ?", obj.ID).Updates(obj).Error

}

func (obj *K8sYamlTask) FillFrontAllData() {
	dbUser, _ := GetUserById(int(obj.UserID))
	if dbUser != nil {
		obj.CreateUserName = dbUser.Username
	}

	dbTemp, _ := GetK8sYamlTemplateById(int(obj.TemplateId))
	if dbTemp != nil {
		obj.TemplateName = dbTemp.Name
		yamlString := dbTemp.Content
		for _, kv := range obj.Variables {
			kvs := strings.Split(kv, "=")
			if len(kvs) != 2 {
				continue
			}
			k := kvs[0]
			v := kvs[1]
			yamlString = strings.ReplaceAll(yamlString, k, v)
		}
		obj.YamlString = yamlString

	}

	obj.VariablesFront = strings.Join(obj.Variables, "\n")

	obj.Key = fmt.Sprintf("%d", obj.ID)

}
func GetK8sYamlTaskAll() (objs []*K8sYamlTask, err error) {
	err = Db.Find(&objs).Error
	return
}

func GetK8sYamlTaskCount() int {
	var count int64
	Db.Table("form_designs").Count(&count)
	return int(count)
}

// select * from ecs where
func GetK8sYamlTaskByIdsWithLimitOffset(ids []int, limit, offset int) (objs []*K8sYamlTask, err error) {
	err = Db.Limit(limit).Offset(offset).Find(&objs, ids).Error
	return
}

func GetK8sYamlTaskByInstanceId(instanceId string) (*K8sYamlTask, error) {

	var dbObj K8sYamlTask
	err := Db.Where("instance_id = ?", instanceId).Preload("FlowNodes").First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("K8sYamlTask不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetK8sYamlTaskById(id int) (*K8sYamlTask, error) {

	var dbObj K8sYamlTask
	err := Db.Where("id = ?", id).First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("K8sYamlTask不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetK8sYamlTaskByTemplateId(templateId uint) (objs []*K8sYamlTask, err error) {

	err = Db.Where("template_id = ?", templateId).Find(&objs).Error
	return

}
